package com.fanshuai.mybatis_plus.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fanshuai.mybatis_plus.dao.UserTokenDao;
import com.fanshuai.mybatis_plus.domain.UserToken;
import com.fanshuai.mybatis_plus.entity.UserTokenEntity;
import com.fanshuai.mybatis_plus.repository.UserTokenRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class UserTokenRepositoryImpl implements UserTokenRepository {
    @Resource
    private UserTokenDao userTokenDao;

    private UserTokenEntity toEntity(UserToken token) {
        UserTokenEntity entity = new UserTokenEntity();
        BeanUtils.copyProperties(token, entity);
        return entity;
    }

    private UserToken toDomain(UserTokenEntity entity) {
        UserToken token = new UserToken();
        BeanUtils.copyProperties(entity, token);
        return token;
    }

    @Override
    public void insert(UserToken token) {
        userTokenDao.save(toEntity(token));
    }

    @Override
    public void update(UserToken token) {
        userTokenDao.updateById(toEntity(token));
    }

    @Override
    public UserToken query(long uid, int client) {
        QueryWrapper<UserTokenEntity> wrapper = new QueryWrapper<UserTokenEntity>();
        wrapper.eq("user_id", uid);
        wrapper.eq("client", client);

        UserTokenEntity entity = userTokenDao.getOne(wrapper);
        return toDomain(entity);
    }

    @Override
    public UserToken queryByAccessToken(String accessToken) {
        UserTokenEntity entity = userTokenDao.queryByAccessToken(accessToken);
        return toDomain(entity);
    }

    @Override
    public UserToken queryByRefreshToken(String refreshToken) {
        UserTokenEntity entity = userTokenDao.queryByRefreshToken(refreshToken);
        return toDomain(entity);
    }
}
